package com.wanghua.spring.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import java.io.*;

public class FileUtil {
    private static Log log = LogFactory.getLog(FileUtil.class);
    public static final String FOLDER_NAME = "/upload/";  //上传文件夹名称

    public static File[] saveFiles(File[] files, String[] names) {  //复制多个文件
        if (files == null)
            return null;
        File root = new File(ServletActionContext.getServletContext().getRealPath(FOLDER_NAME)); //获取上传文件夹绝对路径
        File[] destinies = new File[files.length];  //创建目标文件数组
        for (int i = 0; i < files.length; i++) {  //依次复制每个文件
            File destiny = new File(root, names[i]);  //目标文件
            destinies[i] = destiny;  //放到要返回的数组中
            copy(files[i], destiny);  //复制文件内容
        }
        return destinies;
    }

    public static void copy(File from, File to) {
        System.out.println("Copy: " + from.getAbsolutePath() + " -> " + to.getAbsolutePath());  // from.getAbsolutePath() 值是个 xxx.tmp 临时文件，请求完后会自动删除的。
        InputStream ins = null;
        OutputStream ous = null;
        try {
            to.getParentFile().mkdirs();  //创建所有的上级文件夹
            ins = new FileInputStream(from);
            ous = new FileOutputStream(to);
            byte[] b = new byte[1024];
            int len;
            while ((len = ins.read(b)) != -1) {
                ous.write(b, 0, len);
            }
        } catch (Exception e) {
            log.error(e, e);
        } finally {
            if (ous != null)
                try {
                    ous.close();
                } catch (IOException el) {
                    log.error(el, el);
                }
            if (ins != null)
                try {
                    ins.close();
                } catch (IOException e) {
                    log.error(e, e);
                }
        }
    }
}
